#include "RenderTestViewportClient.h"
#include "Runtime/Engine/Public/CanvasTypes.h"
#include "Runtime/Engine/Public/CanvasItem.h"
#include "Engine/TextureRenderTarget2D.h"


FRenderTestViewportClient::FRenderTestViewportClient()
{
	FString FileName = FPaths::Combine(FPaths::GameSourceDir(), TEXT("data\\Result.PNG"));
	renderer.LoadImageToTexture2DEx(FileName, OutRawData, Width, Height);
	renderer.LoadImageToTexture2D(FileName, InTexture, Width, Height);
	RenderTarget = NewObject<UTextureRenderTarget2D>(GetTransientPackage(), NAME_None, RF_Transient);
	RenderTarget->RenderTargetFormat = RTF_RGBA8;
	RenderTarget->InitAutoFormat(Width,Height);
	RenderTarget->ClearColor = FLinearColor::Blue;
	RenderTarget->UpdateResource();
}

void FRenderTestViewportClient::Draw(FViewport* Viewport, FCanvas* Canvas)
{
	/*FCanvasLineItem Line(FVector2D(0, 0), FVector2D(Viewport->GetSizeXY().X, Viewport->GetSizeXY().Y));
	Line.SetColor(FLinearColor::Blue);
	Canvas->DrawItem(Line);*/

	/*Canvas->Clear(FLinearColor::Black);
	if (RenderTarget)
	{
		FCanvasTileItem Tile(FVector2D::ZeroVector, RenderTarget->Resource, Viewport->GetSizeXY(), FLinearColor::White);
		Canvas->DrawItem(Tile);

		FCanvasLineItem Line(FVector2D(0, 0), FVector2D(Viewport->GetSizeXY().X, Viewport->GetSizeXY().Y));
		Line.SetColor(FLinearColor::Red);
		Canvas->DrawItem(Line);
	}*/
	
	
	auto region = FUpdateTextureRegion2D(0, 0, 0, 0, Width, Height);
	renderer.UpdateTextureRegion(RenderTarget, 0, 1, region, Width * 4, 0, OutRawData.GetData());
	FString FileName= FPaths::Combine(FPaths::GameSourceDir(),TEXT("data\\Result.PNG"));
	//renderer.SaveRenderTargetToFile(RenderTarget, FileName);
	renderer.Render(RenderTarget);
	FCanvasTileItem Tile(FVector2D::ZeroVector, RenderTarget->Resource, Viewport->GetSizeXY(), FLinearColor::White);
	Canvas->DrawItem(Tile);
}